/**
 * 投放控制列表
 */
define(['../../common/service', '../../common/copybox'],
function( http, CB){
   	var adPublishCondition = {
  		init: function (query) {
			var _this = this;
			$(".ndp-search-wrapper[name=app-name]").search({
				placeholder: I18N.getText('adPublishCondition', 'appNameHolder'),
				name:"app-name"//为了方便serialize 建议设置name 属性
			});
			//列表管理
		$('table[list-manager="adpublishconditionList"]').listManager('init',{
			setTopVal:136//调整吸顶的高度,需要减去这个高度
			,scrollDOM:$('.fmp-article')//监听滚动条
			,supportAjaxPage: true
			,pageCallback:function(query){
				$.extend(_this._query, query);
				_this.getList();
			}
		}, function(query){
			_this.bindSearchEvent();
			_this.bindDetailPageEvent();
			_this.bindEditStatusEvent();
			_this._query = query;
			_this._query.searchName = '';
			_this.getList();
		});

		_this.bindAddProductEvent();
    }
	/*
	 @绑定添加产品事件
	*/
	,bindAddProductEvent : function(){
		var _this = this;
		var _addProductModal= $(".dialog-add-product");
		_addProductModal.modal({
			backdrop: 'static',
			keyboard: false,
			show:false
		});
		//modal初始化
		_addProductModal.on('show.bs.modal', function(){
			_addProductModal.find("input").val("");
			_addProductModal.find("textarea").val("");

			//产品类型
			_addProductModal.find('select[name="product-type"]').empty().select2({
				minimumResultsForSearch: Infinity,
				data : [{id : "-1" , text : I18N.getText('adPublishCondition','setProductType')}, {id : "2" , text : I18N.getText('adPublishCondition','website')}]
			}).unbind("select2:select").on("select2:select",function(e){
				var id = e.params.data.id;
				_addProductModal.find('#mk-pixel-id').show();
				if (-1 == id){
					_addProductModal.find('select[name="product-platform"]').empty().select2({
						minimumResultsForSearch: Infinity,
						data : [{id : "-1" , text : I18N.getText('adPublishCondition','setPlatform')}]
					});
				} else if ("2" == id) {
					_addProductModal.find('select[name="product-platform"]').empty().select2({
						minimumResultsForSearch: Infinity,
						data : [{id : "website" , text : I18N.getText('adPublishCondition','website')}]
					});
				}
			});

			//平台
			_addProductModal.find('select[name="product-platform"]').empty().select2({
				minimumResultsForSearch: Infinity,
				data : [{id : "-1" , text : I18N.getText('adPublishCondition','setPlatform')}]
			});
		});

		//首部不允许有空格
		_addProductModal.off("input", "textarea,input").on("input", "textarea,input", function(e){
			var _title = $(this).val().replace(/(^\s*)/g, "");
			if (_title.length  != $(this).val().length){
				$(this).val(_title);
			}
		});

		//标题输入框禁止回车事件
		_addProductModal.off("keydown", "textarea,input").on("keydown", "textarea,input", function(e){
			//禁止回车
			if (e.keyCode == 13) {
				return false;
			}
		});

		//保存产品事件
		_addProductModal.find('button[commit]').off("click").on("click", function(e){
			//校验
			//产品名称不能为空
			var pN = $.trim(_addProductModal.find('input.product-name').val());
			if ('' == pN){
				Kit.alert2(I18N.getText('adPublishCondition','enterProductName'));
				return false;
			}

			//产品类型必选
			var pT = _addProductModal.find('select[name="product-type"]').val();
			if (-1 == pT){
				Kit.alert2(I18N.getText('adPublishCondition','setProductType'));
				return false;
			}

			//平台必选
			var pF = _addProductModal.find('select[name="product-platform"]').val();
			if (-1 == pF){
				Kit.alert2(I18N.getText('adPublishCondition','setPlatform'));
				return false;
			}

			//像素编号不能为空
			var mkPixelId = $.trim(_addProductModal.find('input.mk-pixel-id').val());
			if ('' == mkPixelId){
				Kit.alert2(I18N.getText('adPublishCondition','enterMkPixelId'));
				return false;
			}

			//产品地址不能为空
			var productUrl = $.trim(_addProductModal.find('textarea').val());
			if ('' == productUrl){
				Kit.alert2(I18N.getText('adPublishCondition','enterProductUrl'));
				return false;
			}

			//构造参数
			var param = {
				prodName : pN,
				prodType : pT,
				prodPlatform : pF,
				prodUrl : productUrl,
				mkPixelId : mkPixelId
			};

			// 发起请求
			//提交数据
			var loadingAray = $('.dialog-add-product .modal-dialog');
			Kit.loading.show(loadingAray);
			http.work('/productmanage/save',param,'POST').then(function(res){
				Kit.loading.hide(loadingAray);
				if ('fail' == res.flag){
					if (402 == res.errorCode){
						Kit.alert2(I18N.getText('adPublishCondition','addRepeated', param.prodName,  param.prodPlatform));
					} else {
						Kit.alert2(res.msg);
					}

					return false;
				}

				_addProductModal.modal("hide");

				//重新刷新列表
				_this.getList();
			});
		});

		//添加产品事件
		$("#addProductDiv").removeClass('hidden');
		var _addProduct = $("#add-product-btn");
		_addProduct.off("click").on("click", function(){
			_addProductModal.modal("show");
		});
	}
	/*
		@绑定搜索事件
		1、搜索事件，并对条件进行验证
		2、加载完成后触发搜索事件
	*/
	,bindSearchEvent: function(){
		var _this = this;
		var _searchAction = $('#search-action'),
			_appName =$('input[name="app-name"]');
		_searchAction.unbind('click');
		_searchAction.bind('click',function(){
			_this._query.searchName = _appName.val() || '';
			_this._query.cPage = 1;
			_this.getList();
		});
	}
	/*
		@获取列表数据
	*/
	,getList:function(){
	 	var _this = this;
	  	var loadingArea = $('.conditions-table');
      	Kit.loading.show(loadingArea);
        http.work('/adpublishcondition/search',_this._query,'POST').then(function(res){
			if (res.flag  == 'fail'){
				Kit.loading.hide(loadingArea);
				return;
			}
			//操作DOM节点更换数据
			var data = res.data;
			var _table = $('table[list-manager="adpublishconditionList"]'),
				_tbody = $('#conditions-grid', _table),
				tmpHtml = '',
				_list = data.conditions;

			for(var i=0; i< _list.length; i++){
				tmpHtml += '<tr data-id="'+ (_list[i].id || '') +'"'
						+ ' data-connObjId="'+ _list[i].connObjId +'"'
						+ ' data-connObjName="'+ _list[i].connObjName +'"'
						+ ' data-prodCfgId="'+ ((typeof(_list[i].prodCfgId) === "undefined") ? '':_list[i].prodCfgId) +'"'
						+ ' data-prodCfgName="'+ _list[i].prodCfgName +'"'
						+ ' data-platform-type="'+ _list[i].prodCfgType +'"'
					    + ' data-productType="'+ ((typeof(_list[i].productType) === "undefined") ? '':_list[i].productType) +'"'
						+ '>'
						+ '<td>'
						+  ( (data.paginator.cPage-1) * data.paginator.pSize +i + 1)
						+ '</td>'
						+ '<td>';
				if(_list[i].operationStatus === 0){
					tmpHtml += '<span class="switcher" style="position:relative;">\
				<label class="no-click" style="cursor: not-allowed;"><input type = "checkbox" class = "scheckbox" name="checkbox-toggle" disabled="disabled"> </label></span>';
				}else{
					tmpHtml += '<span class="switcher" style="position:relative;">';
				}
				if(_list[i].status){
					tmpHtml += '<label class = "active" ><input type = "checkbox" class = "scheckbox" name="checkbox-toggle"></label></span>';
				}else{
					tmpHtml += '<label><input type = "checkbox" class = "scheckbox" name="checkbox-toggle"></label></span>';
				}
				tmpHtml +='<i data-swchon-text="ON" data-swchoff-text="OFF"></i>'
						+ '</label>'
						+ '</td>'
						+ '<td title="' + _list[i].connObjName + '">'
						+ _list[i].connObjName
						+ '</td>'
						+ '<td title="'+ _list[i].prodCfgName +'">'
						+ _list[i].prodCfgName
						+ '</td>'
						+ '<td><i class="icon-btn fa fa-'+ (_list[i].operationStatus === 0 ? 'edit' : 'pencil') +'"></i>'
						+ '<button type="button" class="btn btn-link edit-action">'
						+ (_list[i].operationStatus === 0 ? I18N.getText('adPublishCondition','set') : I18N.getText('adPublishCondition','edit'))
						+ '</button>'
					+ '</td>'
						+ '<td title="'+ (_list[i].operationTime || '') +'">'
						+ (_list[i].operationTime == undefined ? '--' : _list[i].operationTime)
						+ '</td>'
						+ '</tr>';
			}
			_tbody.html(tmpHtml);
		  	_table.listManager([{'resetTd':false, 'resetPageData': data.paginator}]);
		  	Kit.loading.hide(loadingArea);
		});
	}
	/*
		@绑定更改状态事件
	*/
	,bindEditStatusEvent: function(){
		var _this = this;
		var _tbody = $('#conditions-grid');
		_tbody.off('click', '.switcher');
		_tbody.on('click', '.switcher', function(e){
			var _toggle 	= $(this),
				 _action	= $('input[name="checkbox-toggle"]', _toggle),
				_tr 		= _action.parents('tr').eq(0),
				_id 		= _tr.attr('data-id'),
				_editAction;
			if(_action.parent().hasClass('no-click')){
				_editAction = _tr.find('.edit-action');
				_editAction.animate({
					opacity: 0.3
				},300);
				_editAction.animate({
						opacity: 1
				},300);
				_editAction.animate({
					opacity: 0.3
				},300);
				_editAction.animate({
						opacity: 1
				},300);
				Kit.alert2(I18N.getText('adPublishCondition','setFirst'))
				return false;
			}
			if(_toggle.hasClass('edit-ing')){
				return false;
			}

			var par = {
				id: _id,
				status: _action.parent().hasClass("active") ? 0 : 1
			}
			var _loadIcon = $('<span class="fa fa-refresh refresh-rotation"></span>');
			_toggle.append(_loadIcon);
			_toggle.addClass('edit-ing');

	        http.work('/adpublishcondition/updateStatus', par,'POST').then(function(res){
				if(res.flag == 'success'){
					 //_action.get(0).checked = res.data.status == 1 ? true : false;
					if(res.data.status == 1)
						_action.parent().addClass("active");
					else
						_action.parent().removeClass("active");
				}
				else{
            		Kit.alert2(res.msg || I18N.getText('adPublishCondition','editFailed'));
				}
				_toggle.removeClass('edit-ing');
				_loadIcon.fadeOut(300,function(){
					$(this).remove();
				});
			});
			return false;
		});
	}
	/*
		@绑定详情页事件
	*/
	,bindDetailPageEvent: function(){
		var _this = this,
			_detailPage = $("#detail-page"),
			_data;
		var _objAndProdCfg 		= $('input[name="obj-and-prodCfg"]', _detailPage),	//应用及平台
			_connObjSimpleName  = $('input[name="connObjSimpleName"]', _detailPage), //应用名简称
			_mainPage	 		= $('select[name="mainPage"]', _detailPage), 		//主页
			_fullRegion			= $('.fullRegion', _detailPage),					    //全球
			_includeRegion		= $('.includeRegion', _detailPage),					//指定地区
			_regionAndPrices 	= $('.regionAndPrices', _includeRegion),			    //指定地区及单价
			_excludeRegion  	= $('.excludeRegion', _detailPage),					//不投放的地区
			_minAge				= $('select[name="ageMin"]', _detailPage),			//最小年龄
			_maxAge				= $('select[name="ageMax"]', _detailPage),			//最大年龄
			_sex				= $('input[name="sex"]', _detailPage),				//性别
			_accounts			= $('input[name="accounts"]', _detailPage),			//账号组
			_cpaConfig			= $('#cpa-config', _detailPage),					    //账号CPA属性
			_bidType			= $('.bid-type-area', _detailPage);					//出价上限


		//生成详细页弹出框
		_detailPage.modal({
			backdrop: 'static',
			keyboard: false,
			show:false
		});

		//限制合法的金额输入
		_detailPage.find('.price-area>input').numeral({'scale': 2});

		//绑定确定事件
		//绑定弹出框关闭事件
		$('button[commit]', _detailPage).click(function(){
			saveCondition(function(){
				_detailPage.modal('hide');
			});
		});

		//详细页打开后加载数据
		_detailPage.on('shown.bs.modal', function(){
			_detailPage.removeAttr('tabindex');  //解决：tabindex=-1 and  overflow-y:auto时 会触发select2的搜索框不可选
			//应用及平台
			_objAndProdCfg.val(_data.connObjName + ' ( ' + _data.prodCfgName + ' ) ' || '');
			//应用名称简称
			_connObjSimpleName.val(_data.connObjSimpleName || '');
			//主页
			_mainPage.val(_data.pageId || -1).trigger('change');

			//账号组
			var _accHtml = '',
				_ccHtml = '';
			if(!_data.accounts){
				_data.accounts = [];
			}
			$.each(_data.accounts, function(i, v){
				if(i != 0){
					_accHtml += ',';
				}
				_accHtml += v.displayName;
				_ccHtml += '<tr data-name="'+ v.displayName +'" data-id="'+ v.fbAccountId +'">'
						 + '<td style="text-align: left; padding-left:20px !important;">'
						 + v.displayName
						 + '</td>'
						//  + '<td  data-status style="border-left:0px;text-align: left; padding-left:20px !important;">'
					    //  + '<input type="hidden" name="checkbox-toggle" value="'+(v.isSupportCPA == 1)+'">'
						//  + (v.isSupportCPA == 0 ? I18N.getText('adPublishCondition', 'accessNot') : I18N.getText('adPublishCondition', 'access'))
						//  + '</td>'
						 + '</tr>';
			});
			_accounts.val(_accHtml);
			_accounts.data('data-list', _data.accounts);
			_cpaConfig.html(_ccHtml || '');

			//出价上限
			if(!_data.priceLimit){
				_data.priceLimit = {}
			}


			//账号CPA属性
			//区分外链产品处
			var bidDiv = $(".condition-table tbody")
			console.log(_data.productType)
			if(_data.productType === 'outlink')
			{
				//产品目录
				var _bidOutLinkHtml = '<tr>' +
					'<td style="text-align:left;padding-left:20px;border-right:0px;">' + I18N.getText('adPublishCondition','linkClicks') + '</td> ' +
					'<td style="border-left: 0px;"> ' +
					'<label>' + I18N.getText('adPublishCondition','impression') + '</label> <div class="no-padding relative price-area">' +
					' <input type="text" class="form-control" name="pricelimit_c_i"> <span class="money-unit-position">$</span> </div> ' +
					'<label>' + I18N.getText('adPublishCondition','linkClick') + '</label> <div class="no-padding relative price-area"> ' +
					'<input type="text" class="form-control" name="pricelimit_c_c"> <span class="money-unit-position">$</span> </div> ' +
					'</td> </tr>';
				_bidOutLinkHtml += '<tr><td style="text-align:left;padding-left:20px;border-right:0px;">' + I18N.getText('adPublishCondition','impression') + '</td> ' +
					'<td style="border-left: 0px;"> ' +
					'<label>' + I18N.getText('adPublishCondition','impression') + '</label> <div class="no-padding relative price-area">' +
					' <input type="text" class="form-control" name="pricelimit_i_i"> <span class="money-unit-position">$</span> </div> ' +
					'</td> </tr>' +
				    '<tr><td style="text-align:left;padding-left:20px;border-right:0px;">' + I18N.getText('adPublishCondition','conversionEvents') + '</td> ' +
					'<td style="border-left: 0px;"> ' +
					'<label>' + I18N.getText('adPublishCondition','impression') + '</label> <div class="no-padding relative price-area">' +
					' <input type="text" class="form-control" name="pricelimit_o_i"> <span class="money-unit-position">$</span> </div> ' +
					'</td> </tr>';
				bidDiv.html(_bidOutLinkHtml);
				$('input[name="pricelimit_c_i"]').val(_data.priceLimit.c_i != undefined && _data.priceLimit.c_i != '' ? Number(_data.priceLimit.c_i / 100).toFixed(2) :  '');  //链接点击量_展示次数   上限
				$('input[name="pricelimit_c_c"]').val(_data.priceLimit.c_c != undefined ? Number(_data.priceLimit.c_c / 100).toFixed(2) : '');  //链接点击量_链接点击量 上限
				$('input[name="pricelimit_i_i"]').val(_data.priceLimit.i_i != undefined ? Number(_data.priceLimit.i_i / 100).toFixed(2) : '');  //展示次数_展示次数 上限
				$('input[name="pricelimit_o_i"]').val(_data.priceLimit.o_i != undefined ? Number(_data.priceLimit.o_i / 100).toFixed(2) : '');  //转化事件_展示次数 上限
				_detailPage.find('.price-area>input').numeral({'scale': 2});
			}
			else
			{
				var _bidHtml = '<tr>' +
					'<td style="text-align:left;padding-left:20px;border-right:0px;">' + I18N.getText('adPublishCondition','appInstalls') + '</td>' +
					'<td style="border-left: 0px;">' +
					'<label>' + I18N.getText('adPublishCondition','impression') + '</label><div class="col-md-2 no-padding relative price-area"> ' +
					'<input type="text" class="form-control" name="pricelimit_a_i"> <span class="money-unit-position">$</span> </div> ' +
					'<label>' + I18N.getText('adPublishCondition','appInstall') + '</label><div class="col-md-2 no-padding relative price-area"> ' +
					'<input type="text" class="form-control" name="pricelimit_a_a"> <span class="money-unit-position">$</span> </div> ' +
					'</td></tr>' +
					'<tr>' +
					'<td style="text-align:left;padding-left:20px;border-right:0px;">' + I18N.getText('adPublishCondition','linkClicks') + '</td> ' +
					'<td style="border-left: 0px;"> ' +
					'<label>' + I18N.getText('adPublishCondition','impression') + '</label> <div class="no-padding relative price-area">' +
					' <input type="text" class="form-control" name="pricelimit_c_i"> <span class="money-unit-position">$</span> </div> ' +
					'<label>' + I18N.getText('adPublishCondition','linkClick') + '</label> <div class="no-padding relative price-area"> ' +
					'<input type="text" class="form-control" name="pricelimit_c_c"> <span class="money-unit-position">$</span> </div> ' +
					'</td> </tr>';
				bidDiv.html(_bidHtml);
				$('input[name="pricelimit_a_i"]').val(_data.priceLimit.a_i != undefined ? Number(_data.priceLimit.a_i / 100).toFixed(2) : '');   //应用安装量_展示次数  上限
				$('input[name="pricelimit_a_a"]').val(_data.priceLimit.a_a != undefined ? Number(_data.priceLimit.a_a / 100).toFixed(2) : ''); //应用安装量_应用安装   上限
				$('input[name="pricelimit_c_i"]').val(_data.priceLimit.c_i != undefined ? Number(_data.priceLimit.c_i / 100).toFixed(2) :  '');  //链接点击量_展示次数   上限
				$('input[name="pricelimit_c_c"]').val(_data.priceLimit.c_c != undefined ? Number(_data.priceLimit.c_c / 100).toFixed(2) : '');  //链接点击量_链接点击量 上限
				_detailPage.find('.price-area>input').numeral({'scale': 2});
			}
		});
		/**
			初始化详细页组件
		*/
		//初始化主页
		_this.initMainPage();
		////初始化地区及单价
		//_this.initRegionAndPrices();
		////初始化年龄段
		//_this.initAge();
		//初始化性别
		//_this.initSex();
		//初始化账号组、账号CPA属性
		_this.initAccounts();
		//打开详情页事件
		$('table[list-manager]').off('click', '.edit-action');
		$('table[list-manager]').on('click', '.edit-action', function(){
			var _editAction = $(this),
				_tr = _editAction.parents('tr').eq(0),
				_id = _tr.attr('data-id');
			_this.editTr = _tr;
			var par = {
				id : _id || ''
			}
			_data = {};
			_data.connObjId 	= _tr.attr('data-connObjId');
			_data.connObjName 	= _tr.attr('data-connObjName');
			_data.prodCfgId 	= _tr.attr('data-prodCfgId');
			_data.prodCfgName 	= _tr.attr('data-prodCfgName');
			_data.productType   = _tr.attr('data-productType');
			//如果当前数据无ID，那么判定为设置详情页
			if(par.id == ''){
				_detailPage.modal('show');
				_detailPage.data('condition', _data);
				return false;
			}
			//以下判定为修改详情页
			if(_editAction.find('i').length > 0){  //防止多次点击
				return false;
			}
			var _loadIcon = $('<i class="fa fa-refresh refresh-rotation" style="display:none;"></i>');
			_editAction.append(_loadIcon).css('marginRight', '-16px');
			_loadIcon.fadeIn(300);
	        http.work('/adpublishcondition/loadDetail', par,'POST').then(function(res){
	        	var data = res.data;
	        	if(res.flag == 'success'){
	        		_loadIcon.fadeOut(300,function(){
						_loadIcon.remove();
						_editAction.css('marginRight', '0px');
						_data = $.extend(_data, data);
						_detailPage.modal('show');
						_detailPage.data('condition', _data);
					});
	        	}else{
	        		Kit.alert2(res.msg || I18N.getText('adPublishCondition','getDetailsFailed'))
	        	}
			});
		});

		//保存
		function saveCondition(cb){
			var _data =_detailPage.data('condition');
			var _par = {
				conditionId			: _data.conditionId 		|| '',	//条件ID
				connObjId			: _data.connObjId 			|| '',	//应用ID
				connObjName			: _data.connObjName 		|| '',	//应用名称
				prodCfgId			: _data.prodCfgId 			|| '',	//平台ID
				prodCfgName			: _data.prodCfgName 		|| '',  //平台名称
				productType			: _data.productType 		|| '',  //产品类型
				pageId				: _mainPage.select2('val') 	|| '',	//主页ID
				connObjSimpleName	: _connObjSimpleName.val() 	|| '',	//应用名称简称
				accounts: []
			}
			//验证主页
			if((_par.pageId == '')||(_par.pageId == -1)){
				Kit.alert2(I18N.getText('adPublishCondition','selectPage'));
				return false;
			}

			//账号数据采集与验证
			var _cpaConfigTr = $('tr', _cpaConfig);
			//账号必选
			if(_cpaConfigTr.length == 0){
				Kit.alert2(I18N.getText('adPublishCondition','selectAccount'));
				return false;
			}

			var _accountsData = [];
			$.each(_cpaConfigTr, function(i, v){
				v = $(v);
				_accountsData.push({
					fbAccountId: v.attr('data-id'),
					displayName: v.attr('data-name'),
					isSupportCPA: $('td[data-status]', v)
								  .find('input[name="checkbox-toggle"]').prop('checked')? 1 : 0
				});
			});
			_par.accounts = _accountsData;

			var _a_i 				= $('input[name="pricelimit_a_i"]'), 	//出价上限 -- 应用安装量-展示次数
				_a_a				= $('input[name="pricelimit_a_a"]'), 	//出价上限 -- 应用安装量-应用安装
				_c_i				= $('input[name="pricelimit_c_i"]'), 	//出价上限 -- 链接点击量-展示次数
				_c_c 				= $('input[name="pricelimit_c_c"]'), 	//出价上限 -- 链接点击量-链接点击量
				_i_i 				= $('input[name="pricelimit_i_i"]'), 	//出价上限 -- 展示次数-展示次数
				_o_i 				= $('input[name="pricelimit_o_i"]'); 	//出价上限 -- 单日独立覆盖-展示次数
			_par.priceLimit = {
				c_i : Number(Number(_c_i.val()) * 100).toFixed(0), //链接点击量_展示次数  上限  转成美分
				c_c : Number(Number(_c_c.val()) * 100).toFixed(0) //链接点击量_链接点击量 上限  转成美分
			}
			//验证出价上限
			if(_data.productType === 'outlink')
			{
				if(!verifyTheBid(_i_i.val())){
					return false;
				}
				if(!verifyTheBid(_o_i.val())){
					return false;
				}
				_par.priceLimit.i_i = Number(Number(_i_i.val()) * 100).toFixed(0); //展示次数_展示次数 上限  转成美分
				_par.priceLimit.o_i = Number(Number(_o_i.val()) * 100).toFixed(0); //转化事件_展示次数 上限  转成美分
			}
			else
			{
				if(!verifyTheBid(_a_i.val())){
					return false;
				}
				if(!verifyTheBid(_a_a.val())){
					return false;
				}
				_par.priceLimit.a_i = Number(Number(_a_i.val()) * 100).toFixed(0); //应用安装量_展示次数  上限  转成美分
				_par.priceLimit.a_a = Number(Number(_a_a.val()) * 100).toFixed(0); //应用安装量_应用安装  上限  转成美分
			}
			if(!verifyTheBid(_c_i.val())){
				return false;
			}
			if(!verifyTheBid(_c_c.val())){
				return false;
			}


			function verifyTheBid(_value_){
				if($.trim(_value_) == '' || Number(_value_) <= 0){
					// Kit.alert2(I18N.getText('adPublishCondition','priceVerify'));
					// return false;
				}
				return true;
			}


			//提交数据
			var loadingAray = $('#detail-page .modal-dialog');
			Kit.loading.show(loadingAray);
			var _editAction = $('.edit-action', _this.editTr);
			var _loadIcon = $('<i class="fa fa-refresh refresh-rotation" style="display:none;"></i>');
			_editAction.append(_loadIcon).css('marginRight', '-16px');
			_loadIcon.fadeIn(300);
	        http.work('/adpublishcondition/save', _par,'POST').then(function(res){
	        	var data = res.data;
				if(res.flag == 'success'){
					_this.editTr.attr('data-id', data.conditionId);
					//将修改投放状态功能释放
					$('.no-click', _this.editTr).css('cursor','pointer');
					$('.no-click', _this.editTr).removeClass('no-click');
					$('[disabled]', _this.editTr).removeAttr('disabled');
					typeof(cb) == 'function' ? cb() : '';
				}else{
					Kit.alert2(res.msg || I18N.getText('adPublishCondition','saveFailed'))
				}
				Kit.loading.hide(loadingAray);
				//保存后，修改DOM节点
				_loadIcon.fadeOut(300,function(){
					$(this).remove();
					$('.edit-action', _this.editTr).text(I18N.getText('adPublishCondition','edit'));
					$('.edit-action', _this.editTr).css('margin-right', '0px');
				});
			});
		}
	}

	/*
		@初始化主页
	*/
	,initMainPage: function(){
		var _this = this;
		var _mainPage = $('select[name="mainPage"]'),
		 	_loadAray = _mainPage.parents('div').eq(0);
		Kit.loading.show(_loadAray);
	    http.work('/page/getPages','POST').then(function(res){
	    	var data = res.data;
			if(res.flag == 'success'){
				data = _.sortBy(data,function (item) {return item.name.toLowerCase();});
				var tmpHtml = '<option value="-1">' + I18N.getText('adPublishCondition','selectPage') + '</option>';
				for(var i = 0; i<data.length; i++){
					tmpHtml += '<option img="'+data[i].pictureUrl+'" request-link="'+data[i].link+'" value="'+data[i].fbPageId+'">'+data[i].name+'</option>';
				}
				_mainPage.html(tmpHtml);
				_mainPage.select2({
					//打开
					templateResult: function(item){
						if(!item.id || item.id == -1){
							return item.text;
						}
						var _t =  '<div class="select3-icon"><img src="' + $(item.element).attr("img")
								+ '" class="fb-icon" width="26"/></div>'
								+ '<div class="select3-page">'
						 		+ '<span class="select3-page-name" title="'+ item.text +'">'
						   		+ item.text
						   		+ '</span>'
						   		+ '<span class="select3-page-link" title="'+ $(item.element).attr('request-link') +'">'
						   		+ $(item.element).attr('request-link')
						   		+ '</span>'
						   		+ '</div>';
						return $(_t);
					},
					//选中
					templateSelection: function(item){
						if(!item.id ||item.id == -1){
							return item.text;
						}
						return $('<span><img src="' + $(item.element).attr("img") + '" class="fb-icon" width="26"/>'+ item.text + '</span>');
					}
				});
			}else{
				Kit.alert2(res.msg || I18N.getText('adPublishCondition','getPagesFailed'))
			}
			Kit.loading.hide(_loadAray);
		});
	}
	/*
		@初始化地区及单价
	*/
	,initRegionAndPrices: function (){
		var _this = this;

		//绑定全球与指定地区切换事件
		var _regionRadio = $('[name="region-radio"]');
		_regionRadio.unbind('click');
		_regionRadio.bind('click', function(){
			var _action = this,
				_radioCon;
			$.each(_regionRadio, function(i, v){
				_radioCon = $(v).closest('.radio-con');
				if(v == _action){
					_radioCon.removeClass('not-available');
					_radioCon.find('input[type="text"]').removeAttr("readonly");
				}else{
					_radioCon.addClass('not-available');
					_radioCon.find('input[type="text"]').attr("readonly", "readonly");
				}
			});
			if(_action.value == 'include'){
				var _liList = $('.regionAndPrices .select2-selection__rendered li');
				_liList.length == 1 ? $('.select2-search__field', _liList).width(300) : '';
			}
		});
		_regionRadio.eq(0).trigger('click');
		//初始化select2
		function initLocationSelect2(onlyLB, placeholderText){
			var _cType;
			$('select[name="location"]', onlyLB).select2({
				placeholder: placeholderText,
				multiple: true,
				allowClear: false,
				width: '100%',
				minimumInputLength: 1,
				ajax:{
					type:'POST',
					url: cors_config.api_host + '/search/searchAdgeolocation',
				    dataType: 'json',
				    delay: 250,
				    data: function (query) {
				    	_cType = onlyLB.find('select[name="location-type"]').val() || 'country';
				    	return{
				    		param:JSON.stringify({
								q: query.term,
								locale: I18N.language,
								cType: _cType
							})
				    	}
				    },
				    xhrFields: {
	                    withCredentials: true
	                },
				    //配置返回数据格式
					processResults: function (res, param) {
						var opts = {
							results: []
						};
						var data = res.data;
						$(data).each(function(i, v) {
							if(_cType == 'country'){
								opts.results.push({
									id: v.countryCode,
									text: v.name + '(' + v.countryCode +')',
									countryCode: v.countryCode,
									name:v.name,
									cType: 'country',
									key	: v.key,
									supportsRegion: v.supportsRegion,
									supportsCity : v.supportsCity
								});
							}else if(_cType == 'city'){
								opts.results.push({
									id: v.key,
									text: v.name,
									countryCode: v.countryCode,
									name:v.name,
									cType: 'city',
									key	: v.key,
									supportsRegion: v.supportsRegion,
									supportsCity : v.supportsCity
								});
							}
						});
						return opts;
				    },
				    cache: false
				 }
			}).on("select2:open",function(e){
	            _this.bindCopyToLocation($(this).closest('.only-lb'));  //绑定copy事件
	        });
		}

		initLocationSelect2($('.excludeRegion'), I18N.getText('adPublishCondition','excludeLocationHolder'));  //初始化不包括区域的select2
		var _html = '<div class="regionBg col-md-12 cbox only-lb mb-10">'
				+ '<div class="col-md-2 no-padding">'
				+ '<select name="location-type" class="form-control no-padding">'
				+ '<option value="country">' + I18N.getText('adPublishCondition','country') + '</option>'
				+ '<option value="city">' + I18N.getText('adPublishCondition','city') + '</option>'
				+ '</select>'
				+ '</div>'
				+ '<div class="col-md-8">'
				+ '<select type="text" style="width:240px;" name="location" multiple></select>'
				+ '</div>'
				+ '<div class="col-md-2 no-padding relative price-area">'
				+ '<input type="text" class="form-control" name="prices" placeholder="' + I18N.getText('adPublishCondition','price') + '"/>'
				+ '<span class="money-unit-position">$</span>'
				+ '</div>'
				+ '<a href="javascript:void(0);" cb-del="" class="close closeBtn" style="display: block;">×</a>'
				+ '</div>';
		var cb = new CB.CopyBox($('.regionAndPrices'), {
			box: _html
			,perInit: function($box) {
			}
			,afterAdd: function($box) {
				initLocationSelect2($box, I18N.getText('adPublishCondition','includeLocationHolder'));   //初始化包括区域的select2
				//限制合法的金额输入
				$box.find('input[name="prices"]').numeral({'scale': 2});

			}
			,afterRemove:function(){
			}
		});
		cb.init();
		$('[fb-add]').click(function() {
			cb.add();
		});
	}
	/*
	 	地址区域绑定复制功能
		select2 4.0 DataAdapter 报错 引用full.min.js同样出错
		select2 4.0 对keydown有清除冒泡动作 所以需要延时绑定keydown  用托管事件不起作用
		select2 4.0 unselect事件对原事件可能有销毁  需要在unselect 后再次进行绑定keydown
		触发事件源：select2:open  原因是该插件的展示时后销毁原input dom，且无法将事件代理至 .only-lb
	 * */
	,bindCopyToLocation: function(onlyLB){
		var isCtrlKey   = false,		 //用于处理copy监控偶发性失效问题
			isLoading   = false;		 //用于处理重复粘贴

		var locWarp = $('.includeRegion');
		//禁用鼠标右键粘贴
		onlyLB.off('contextmenu');
		onlyLB.on('contextmenu', function(e){
			e.stopPropagation()
			return false;
		});
		//判定是否为copy操作。触发时间在select2.query之前
		$('.select2-search__field', onlyLB).off('keydown');
		$('.select2-search__field', onlyLB).on('keydown', function(e){
			if(e.ctrlKey|| e.metaKey){
				isCtrlKey = true;
			}
		});

		//绑定copy事件。触发时间在select2.query之后
		onlyLB.off('keyup');
		onlyLB.on('keyup',function(e){
			var onlyLB =$(this),
				loc = $('select[name="location"]', this);
			if(!isLoading && isCtrlKey && e.keyCode == 86){
				var par = {
					countries: $('.select2-search__field', this).val() || '',
					locale:I18N.language
					};
				isLoading = true;
				Kit.loading.show(onlyLB);
				loc.select2('close');
				//$box.find('.select2-input').trigger('blur');
				http.work('/search/searchAdgeolocationList', par, 'POST').then(function(res){
					if(res.flag == 'success'){
						var preload_data = loc.select2('data'),
							_region = [];
						$.each(preload_data, function(i, v) {
							_region.push(v);
						});
						$.each(res.data,function(i,v){
							_region.push({
								id				: v.countryCode,
								text			: v.name + '('+ v.countryCode +')',
								countryCode		: v.countryCode,
								name			: v.name,
								cType			: 'country',
								key				: v.key,
								supportsRegion	: v.supportsRegion,
								supportsCity 	: v.supportsCity
							});
						});
						if(res.data.length == 0){
							Kit.alert2(I18N.getText('adPublishCondition','allNoMatch'));
						}else{
							loc.select2('data', _region);
						}
					}
					isLoading = false;
					Kit.loading.hide(onlyLB);
				});
			}
			window.setTimeout(function(){
				isCtrlKey = false;
			},300);
			return false;
		});

	}
	/*
		@初始化年龄
	*/
	,initAge: function(){
		var _this = this;
		var _ageMin = $('select[name="ageMin"]'),
			_ageMax = $('select[name="ageMax"]'),
			_tmpHtml = '';
		for(var i=13; i< 65; i++){
			_tmpHtml += '<option value="'+ i +'">'+ i +'</option>';
		}
		_ageMin.html(_tmpHtml);
		_tmpHtml += '<option value="65">65+</option>'
		_ageMax.html(_tmpHtml);
		_ageMin.select2();
		_ageMax.select2();
	}

	,initAccounts: function(){
		var _this = this;
		var _detailPage 		= $("#detail-page"),									//详细页DOM
			_accountsInput 		= $('input[name="accounts"]', _detailPage), 			//账号输入框
			_editAccounts 		= $('button[name="detailPageUpdateAccount"]', _detailPage), 					//打开选择账号组事件源
			_accountsDOM 		= $('.dialog-accounts'), 								//选择账号DOM
			_cpaConfig 			= $('#cpa-config', _detailPage);						//账号CPA属性DOM

		//生成选择账号弹出框
		_accountsDOM.modal({
			keyboard: false,
			show:false
		});
			//列表管理
			var settings = {supportDrag: false,supportAdjust:false,supportConfig:false,supportSorting:false,supportRemind:false};
			$('table[list-manager="detailSelectAccountList"]').listManager('init',settings, function(){
				settinAccounts();
			});
			$("#checkbox-account-all").click(function(){
				if (document.getElementById("checkbox-account-all").checked) {
					$("input[name='checkbox-account']").prop("checked", "checked");
				}
				else {
					$("input[name='checkbox-account']").removeAttr("checked");
				}
			});
		//打开弹出框后事件
		_accountsDOM.on('shown.bs.modal', function(){
			settinAccounts();
		});
		//绑定弹出框关闭事件
		$('button[commit]', _accountsDOM).click(function(){
			saveAccountToDetailPage(function(){
				_accountsDOM.modal('hide');
			});
		});
		//打开选择账号弹出框
		$(_editAccounts).unbind('click');
		$(_editAccounts).bind('click' ,function(){
			_accountsDOM.modal('show');
		});
		//配置账号组列表数据
		function settinAccounts(){
			if(!_detailPage.data('condition')){
				console.log('必要的参数丢失，获取数据停止');
				return false;
			}
			var body = {
				param: {}
			}
			body.param.isOutLink = _detailPage.data('condition')['productType'] === 'outlink';
			body.param.connObjId = _detailPage.data('condition')['connObjId'];
			body.param = JSON.stringify(body.param);
			var loadingArea = $('#detail-select-account-content');
			Kit.loading.show(loadingArea);
			var hasAccountId = _cpaConfig.find('tr');
		    http.do('/adpublishcondition/getAccounts',body,'POST').then(function(res){
				var _tbody = $('#detail-select-account-grid'),
					tmpHtml = '',
					data = res.data;
					//生成HTML
					$.each(data, function(i, v){
						tmpHtml += '<tr>';
						tmpHtml += '<td><label>';
						var checked=false;
						$.each(hasAccountId, function(){
							if(v.fbAccountId == $(this).attr('data-id'))
								checked = true;
						});
						console.log(checked );
						if(checked)
							tmpHtml += '<input type="checkbox" name="checkbox-account" data-id="'+ v.fbAccountId+'" data-name="'+ v.displayName+'" isSupportCPA = "'+v.isSupportCPA+'" checked="checked">';
						else
							tmpHtml += '<input type="checkbox" name="checkbox-account" data-id="'+ v.fbAccountId+'" data-name="'+ v.displayName+'" isSupportCPA = "'+v.isSupportCPA+'">';
						tmpHtml += '<span style="margin-left:10px;">'+(i+1)+'</span></label></td>';
						tmpHtml += '<td title="' + v.displayName + '" class="text-left">' + v.displayName + '</td>';
						tmpHtml += '<td title="' + v.isSupportCPA + '" class="text-left">' + (v.isSupportCPA == 0 ? I18N.getText('adPublishCondition', 'accessNot') : I18N.getText('adPublishCondition', 'access')) + '</td>';
						tmpHtml += '</tr>';
					});
					_tbody.html(tmpHtml);
					////临时数据缓存
					//_tbody.find("tr").each(function (i) {
					//	$(this).data("ids", data[i].fbAccounts);
					//});
					$('table[list-manager="detailSelectAccountList"]').listManager('resetTd', true);
					//_this._bindEnents();
					Kit.loading.hide(loadingArea);
			},function (msg) {
				Kit.alert2(msg || I18N.getText('adPublishCondition','getAccountsFailed'));
				Kit.loading.hide(loadingArea);
			});
		}

		accountTimezoneModal();
		//保存选中账号至详细页
		function saveAccountToDetailPage(cb){
			var _domList = _accountsDOM.find('input[name="checkbox-account"]:checked'),//已选中的账号列表DOM
				_tmpCPA	= '',								//临时存储账号CPA拼接字符串
				_dataList = [],								//数据存储变量
				_tmpData = '',								//临时存储账号组拼接字符串
				_isChecked;									//是否为选中状态
			$.each(_domList, function(i, v){
				v = $(v);
				_dataList.push({
					fbAccountId: v.attr('data-id'),
					displayName: v.attr('data-name')
				});
				//至账号组 input
				if(i != 0){
					_tmpData += ',';
				}
				_tmpData += v.attr('data-name');
				_isChecked = v.attr('isSupportCPA') == 1;
				_tmpCPA += '<tr data-name="'+ v.attr('data-name') +'" data-id="'+ v.attr('data-id') +'">'
						 + '<td style="text-align:left; padding-left:20px !important;border-right: 0px;">'
						 + v.attr('data-name')
						 + '</td>'
						 + '<td  data-status style="border-left: 0px;text-align: left; padding-left:20px !important;">'
					     + '<input type="hidden" name="checkbox-toggle" value="'+_isChecked+'">'
						 + (_isChecked ? I18N.getText('adPublishCondition', 'access') : I18N.getText('adPublishCondition', 'accessNot'))
						 + '</td>'
						 + '</tr>';


			});
			_cpaConfig.html(_tmpCPA);
			_accountsInput.val(_tmpData);
			_accountsInput.data('data-list', _dataList);

			typeof(cb) == 'function' ? cb() : '';
		}

		function accountTimezoneModal(){
			var accountsTimezoneModal = $(".dialog-accounts-timezone");
			accountsTimezoneModal.modal({
				backdrop: 'static',
				keyboard: false,
				show: false
			});

			//绑定弹出框关闭事件
			$('button[confirm]', accountsTimezoneModal).click(function(){
				accountsTimezoneModal.modal('hide');
			});

			//取消
			$('button[cancel]', accountsTimezoneModal).click(function(){
				_accAction.removeClass('is-selected');
				_selectedList.children("li:last").remove();
				accountsTimezoneModal.modal('hide');
			});
		}
	}
   }
   return adPublishCondition;
});
